package org.stvd.listener.workflow;

import org.activiti.engine.delegate.event.ActivitiEntityEvent;
import org.activiti.engine.delegate.event.ActivitiEvent;
import org.activiti.engine.runtime.ProcessInstance;
import org.springframework.beans.factory.annotation.Autowired;
import org.stvd.common.workflow.enums.WorkflowApproveStatusEnum;
import org.stvd.core.util.DateUtil;
import org.stvd.entities.workflow.WfIndex;
import org.stvd.service.workflow.WfIndexService;

/**
 * 流程已结束。在最后一个节点的 ACTIVITY_COMPLETED事件之后触发。 当流程到达的状态，没有任何后续连线时， 流程就会结束。
 */
public class ProcessCompletedListener implements EventHandler{

    @Autowired
    WfIndexService wfIndexService;
    
    public void handle(ActivitiEvent event) {
        
        System.out.println("Event received: " + event.getType());

        ActivitiEntityEvent entityEvent = (ActivitiEntityEvent) event;
        ProcessInstance processInstance = (ProcessInstance) entityEvent.getEntity();
        
        WfIndex wfIndex = wfIndexService.findByProcInstId(processInstance.getId());
        if(wfIndex != null){
            wfIndex.setTaskId("");
            wfIndex.setTaskName("结束节点");
            wfIndex.setStatus(WorkflowApproveStatusEnum.Finished.getValue());
            wfIndex.setEndTime(DateUtil.getSystemDate());
            wfIndexService.update(wfIndex);
        }
    }  
}